import pyautogui as pyg
import time
import os

STATUS_FIND_CLICK = 101  # 找到图片并点击
STATUS_FIND = 102  # 只找图片
STATUS_NOT_IMG = 104  # 图片不存在
STATUS_NOT_FOUND = 404  # 没找到图片

# 识图封装 300找图,，点一次，相似度0.9，像素步长5,不灰度
def find_img_click(path, count=300, clicks=1, confidence=0.9, region=(0, 170, 1280, 730), grayscale=False, step=5):
    if not os.path.exists(path):
        print(f"文件 {path.split('/')[-1]} 不存在")
        return STATUS_NOT_IMG
    attempts = 1
    while attempts < count+1:
        try:
            start_time = time.time()
            point = pyg.locateCenterOnScreen(
                path, confidence=confidence, region=region, grayscale=grayscale, step=step)
            if point is not None and clicks:
                for _ in range(clicks):
                    pyg.click(point)
                    time.sleep(0.1)
                click_time = time.time()
                print(
                    f"第{attempts}次 {path.split('/')[-1]} 识别成功,点击{clicks}次 耗时{click_time-start_time:.3f}")
                return STATUS_FIND_CLICK
            elif point is not None and clicks == 0:
                end_time = time.time()
                print(
                    f"第{attempts}次 {path.split('/')[-1]} 识别成功 无点击耗时{end_time-start_time:.3f}")
                return STATUS_FIND
        except pyg.ImageNotFoundException:
            not_find_time = time.time()
            print(
                f"第{attempts}次 {path.split('/')[-1]} 识别失败 耗时{not_find_time-start_time:.3f}")
        attempts += 1
    if count == 300:
        print("未发现图片")
    return STATUS_NOT_FOUND

find_img_click("/image/duanzao_success.png", clicks=1, region=(0, 0, 600, 800))